﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NetWing.Common;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.CommonAPIs;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;


namespace NetWing.BPM.Admin.weixin
{
    public class wxhelper
    {
        /// <summary>
        /// 检查系统用户登录情况
        /// </summary>
        /// <returns></returns>
        public static bool checkLogin()
        {

            bool r = false;//用户登录信息默认false
            if (string.IsNullOrEmpty(CookieHelper.GetCookie("openid")))//假如没有session openid
            {
                //建议用户重新登录用户中心
                //System.Web.HttpContext.Current.Response.Redirect("login.aspx");
                System.Web.HttpContext.Current.Response.Redirect(""+ConfigHelper.GetValue("website")+"/weixin/auth2getcode.aspx");
            }
            else
            {
                string nowuid = "0";
                string usid = CookieHelper.GetCookie("currentUserID");

                string UserName = CookieHelper.GetCookie("currentUserName");

                if (!string.IsNullOrEmpty(CookieHelper.GetCookie("currentUserID")) && !string.IsNullOrEmpty(UserName))
                {
                    nowuid = CookieHelper.GetCookie("currentUserID");
                }
                //!!!!!!!!!!!!!!注意:加上keyid判断用户退出就无法自动登录,如果单纯判断openid则可以自动登录.因为openid是自动获得的
                //检查用户是否注册
                string chksql = "select count(keyid) from Sys_Users where openid='" + CookieHelper.GetCookie("openid").ToString() + "' and keyid=" + nowuid + "";

                int k = (int)SqlEasy.ExecuteScalar(chksql);
                if (k > 0)//已经注册
                {

                    DataRow dr = SqlEasy.ExecuteDataRow("select top 1 * from Sys_Users where openid='" + CookieHelper.GetCookie("openid").ToString() + "'");
                    CookieHelper.WriteCookie("keyid", dr["keyid"].ToString());
                    CookieHelper.WriteCookie("openid", dr["openid"].ToString());
                    CookieHelper.WriteCookie("truename", dr["truename"].ToString());
                    CookieHelper.WriteCookie("nickname", HttpUtility.UrlEncode(dr["weixin"].ToString()));
                    CookieHelper.WriteCookie("mobile", dr["mobile"].ToString());
                    CookieHelper.WriteCookie("idcard", dr["idcard"].ToString());
                    CookieHelper.WriteCookie("DepartmentId", dr["DepartmentId"].ToString());
                    CookieHelper.WriteCookie("loginok", "true");
                    CookieHelper.WriteCookie("headimgurl", dr["headimgurl"].ToString());//头像
                    CookieHelper.WriteCookie("currentUserID", dr["keyid"].ToString());//登录成功,吧用户ID写入cookies


                    string usidyi = CookieHelper.GetCookie("currentUserID");//得到用户id
                    string keyidyi = CookieHelper.GetCookie("keyid");
                    string truenameyi = CookieHelper.GetCookie("truename");
                    string mobileyi = CookieHelper.GetCookie("mobile");
                    string idcardyi = CookieHelper.GetCookie("idcard");
                    string DepartmentIdyi = CookieHelper.GetCookie("DepartmentId");
                    string loginokyi = CookieHelper.GetCookie("loginok");
                    string headimgurlyi = CookieHelper.GetCookie("headimgurl");
                    r = true;
                    //如果已经注册，用户点击那个页面算那个页面，不用跳到用户中心
                    //System.Web.HttpContext.Current.Response.Redirect(CookieHelper.GetCookie("returnurl"));
                }
                else//没有绑定，员工输入手机号，姓名进行绑定
                {
                    //System.Web.HttpContext.Current.Response.Redirect("employeeBind.aspx");
                    r = false;
                }

                //!!!!!!!!!!!!!!注意:加上keyid判断用户退出就无法自动登录,如果单纯判断openid则可以自动登录.因为openid是自动获得的
                //检查客户是否注册
                //string yonhsql = "select count(keyid) from jydUser where openid='" + CookieHelper.GetCookie("openid").ToString() + "' and keyid=" + nowuid + "";

                //int h = (int)SqlEasy.ExecuteScalar(yonhsql);
                ////已经注册
                //if (h > 0)
                //{
                //    DataRow de = SqlEasy.ExecuteDataRow("select * from jydUser where openid='" + CookieHelper.GetCookie("openid").ToString() + "' ");
                //    CookieHelper.WriteCookie("keyid", de["keyid"].ToString());
                //    CookieHelper.WriteCookie("openid", de["openid"].ToString());
                //    CookieHelper.WriteCookie("truename", de["truename"].ToString());
                //    CookieHelper.WriteCookie("nickname", HttpUtility.UrlEncode(de["nickname"].ToString()));
                //    CookieHelper.WriteCookie("mobile", de["mobile"].ToString());
                //    CookieHelper.WriteCookie("idcard", de["idcard"].ToString());
                //    CookieHelper.WriteCookie("DepartmentId", de["DepartmentId"].ToString());
                //    CookieHelper.WriteCookie("loginok", "true");
                //    CookieHelper.WriteCookie("headimgurl", de["headimgurl"].ToString());//头像
                //    CookieHelper.WriteCookie("currentUserID", de["keyid"].ToString());//登录成功,吧用户ID写入cookies


                //    string usidyi = CookieHelper.GetCookie("currentUserID");//得到用户id
                //    string keyidyi = CookieHelper.GetCookie("keyid");
                //    string truenameyi = CookieHelper.GetCookie("truename");
                //    string mobileyi = CookieHelper.GetCookie("mobile");
                //    string idcardyi = CookieHelper.GetCookie("idcard");
                //    string DepartmentIdyi = CookieHelper.GetCookie("DepartmentId");
                //    string loginokyi = CookieHelper.GetCookie("loginok");
                //    string headimgurlyi = CookieHelper.GetCookie("headimgurl");
                //    r = true;
                //    //如果已经注册，用户点击那个页面算那个页面，不用跳到用户中心
                //    //System.Web.HttpContext.Current.Response.Redirect(CookieHelper.GetCookie("returnurl"));
                //}
                //else//没有绑定，员工输入手机号，姓名进行绑定
                //{
                //    //System.Web.HttpContext.Current.Response.Redirect("employeeBind.aspx");
                //    r = false;
                //}
            }
            return r;
        }

        /// <summary>
        /// 发送微信信息
        /// </summary>
        /// <param name="openid">微信用户openid</param>
        /// <param name="content">内容</param>
        public static void SendText(string openid, string content)
        {

            string appid = NetWing.Common.ConfigHelper.GetValue("AppID");
            string appsecret = NetWing.Common.ConfigHelper.GetValue("AppSecret");
            string error = string.Empty;
            var accessToken = "";
            accessToken = AccessTokenContainer.TryGetAccessToken(appid, appsecret);

            if (accessToken == null)
            {
                accessToken = AccessTokenContainer.GetAccessToken(appid);
            }
            else
            {

                //var accessToken = AccessTokenContainer.TryGetAccessToken(appid, appsecret);
                //当前在执行之前，我们需要像以前一样全局注册一下appId和appSecret：
                //AccessTokenContainer.Register(_appId, _appSecret);//全局只需注册一次，例如可以放在Global的Application_Start()方法中。

                //CustomApi.SendText(accessToken, CookieHelper.GetCookie("openid"), "nihao");
                string urlformat = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}";

                var data = new
                {
                    touser = openid,
                    msgtype = "text",
                    text = new
                    {
                        content = content
                    }
                };
                Senparc.Weixin.CommonAPIs.CommonJsonSend.Send(accessToken.ToString(), urlformat, data);
            }
        }


        /// <summary>
        /// 检查客户登录情况
        /// </summary>
        /// <returns></returns>
        public static bool checkUserLogin()
        {
            bool r = false;//用户登录信息默认false
            if (string.IsNullOrEmpty(CookieHelper.GetCookie("useropenid")))//假如没有session openid
            {
                //建议用户重新登录用户中心
                //System.Web.HttpContext.Current.Response.Redirect("login.aspx");
                System.Web.HttpContext.Current.Response.Redirect("auth2getcode.aspx");
            }
            else
            {
                //检查用户是否注册
                string chksql = "select count(keyid) from MJUser where openid='" + CookieHelper.GetCookie("useropenid").ToString() + "' ";
                int k = (int)SqlEasy.ExecuteScalar(chksql);
                if (k > 0)//已经注册
                {
                    DataRow dr = SqlEasy.ExecuteDataRow("select top 1 * from MJUser where openid='" + CookieHelper.GetCookie("useropenid").ToString() + "' ");
                    CookieHelper.WriteCookie("userkeyid", dr["keyid"].ToString());
                    CookieHelper.WriteCookie("useropenid", dr["openid"].ToString());
                    CookieHelper.WriteCookie("userfullname", dr["fullname"].ToString());
                    CookieHelper.WriteCookie("usertel", dr["tel"].ToString());
                    CookieHelper.WriteCookie("usercardid", dr["cardid"].ToString());
                    CookieHelper.WriteCookie("userdepid", dr["depid"].ToString());
                    CookieHelper.WriteCookie("userloginok", "true");
                    CookieHelper.WriteCookie("userheadimgurl", dr["headimgurl"].ToString());//头像
                    r = true;
                    //如果已经注册，用户点击那个页面算那个页面，不用跳到用户中心
                    //System.Web.HttpContext.Current.Response.Redirect(CookieHelper.GetCookie("returnurl"));
                }
                else//没有绑定，员工输入手机号，姓名进行绑定
                {
                    //System.Web.HttpContext.Current.Response.Redirect("employeeBind.aspx");
                    r = false;
                }
            }
            return r;
        }

   /// <summary>
   /// 通用模板消息发送类
   /// </summary>
   /// <param name="openId">要发送对象的openid</param>
   /// <param name="templateId">模板消息ID</param>
   /// <param name="linkUrl">链接地址</param>
   /// <param name="templateData">要发送的消息内容</param>
   /// <returns>如果返回 请求成功 那么就发送成功,否则返回错误</returns>
        public static string sendTemplateMsg(string openId, string templateId, string linkUrl,object templateData)
        {
            string r = "";//发送结果
            try
            {
                //根据appId判断获取  
                if (!AccessTokenContainer.CheckRegistered(NetWing.Common.ConfigHelper.GetValue("AppID")))    //检查是否已经注册  
                {
                    AccessTokenContainer.Register(NetWing.Common.ConfigHelper.GetValue("AppID"), NetWing.Common.ConfigHelper.GetValue("AppSecret"));    //如果没有注册则进行注册  
                }
                string access_token = AccessTokenContainer.GetAccessTokenResult(NetWing.Common.ConfigHelper.GetValue("AppID")).access_token; //AccessToken

                SendTemplateMessageResult sendResult = TemplateApi.SendTemplateMessage(access_token, openId, templateId, linkUrl, templateData);
                if (sendResult.errcode.ToString() == "请求成功")
                {
                    r = "请求成功";
                }
                else
                {
                    r = sendResult.errmsg;
                }
            }
            catch (Exception err)
            {
                r = err.Message;
                throw;
            }
            //发送成功
            return r;
        }

 

    }
}